//
//  MaMapView.m
//  xmgjAppFront
//
//  Created by ZekiMini on 2020/8/24.
//  Copyright © 2020 guojutech. All rights reserved.
//

#import "MapView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "GJOrderAnnotaion.h"
#import "GJNumberAnnotationView.h"
#import "GJNumberAnnotation.h"
#import "GJMapHUDView.h"
@interface MapView ()<MAMapViewDelegate>
@property (nonatomic, strong)MAMapView *mapView;
@property (nonatomic, strong)UIView *dispatchGoodsButton;
@property (nonatomic, strong) UIButton *locationBtn;//定位按钮
@property (nonatomic, assign) int zoomLevel;
@property (nonatomic, strong)NSDictionary *iconNameDic;
@property (nonatomic, strong)MAPointAnnotation *userAnnotation;//定位的点
@end
static CGFloat KDispatchGoodsButtonWidth = 72;
static CGFloat KDispatchGoodsSubViewWidth = 60;
@implementation MapView

- (instancetype)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    [self initlizationSubviews];
  }
  return self;
}

- (void)initlizationSubviews{
  [self addSubview:self.mapView];
  [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self);
  }];
  //  GJMapHUDView *hud = [GJMapHUDView new];
  //  [self.mapView addSubview:hud];
  //  [hud mas_makeConstraints:^(MASConstraintMaker *make) {
  //    make.top.mas_equalTo(16);
  //    make.right.mas_equalTo(-63);
  //    make.left.mas_equalTo(63);
  //    make.height.mas_equalTo(36);
  //  }];
  //  hud.numberString = @"888";
  //
  //  [self.mapView addSubview:self.dispatchGoodsButton];
  //  [self.dispatchGoodsButton mas_makeConstraints:^(MASConstraintMaker *make) {
  //    make.centerX.equalTo(self.mapView);
  //    make.bottom.equalTo(self.mas_bottom).offset(-kSafeTabBarHeight - 32);
  //    make.width.height.mas_equalTo(KDispatchGoodsButtonWidth);
  //  }];
  //  [self.mapView addSubview:self.locationBtn];
  //  [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  //    make.left.mas_equalTo(16);
  //    make.centerY.equalTo(self.dispatchGoodsButton);
  //    make.width.height.mas_equalTo(38);
  //  }];
}



- (void)addLineToMapView:(NSDictionary *)pointData{
  [self setupLine:pointData[@"list"]];
}
- (void)setupLine:(NSArray *)dataList {
  CLLocationCoordinate2D points[dataList.count];
  
  for (NSInteger i = 0; i < dataList.count; i++) {
    NSDictionary *object = dataList[i];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([object[@"lat"] doubleValue],
                                                                   [object[@"lon"] doubleValue]);
    points[i] = coordinate;
  }
  NSMutableArray *lines = [NSMutableArray new];
  MAPolyline *polyLine = [MAPolyline polylineWithCoordinates:points count:dataList.count];
  [lines addObject:polyLine];
  [self.mapView addOverlays:lines];
  [self.mapView showOverlays:lines animated:YES];
}

- (void)addAnnotationsWithIcon:(NSString *)icon list:(NSArray *)list{
  __block NSMutableArray *annotations = [NSMutableArray array];
  
  //移除原有的
  [self.mapView.annotations each:^(MAPointAnnotation *object) {
    if (object != self.userAnnotation) {
      [self.mapView removeAnnotation:object];
    }
  }];
  if (list.count <= 0) {
    return;
  }
  
  [list each:^(NSDictionary *object) {
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([object[@"lat"] doubleValue], [object[@"lon"] doubleValue]);
    GJOrderAnnotaion *annotation = [[GJOrderAnnotaion alloc]init];
    annotation.icon = icon;
    annotation.coordinate = coordinate;
    [annotations addObject:annotation];
  }];
  
  [self.mapView addAnnotations:annotations];
  
  
  //  [self addCarNumberAnnotation:@[@{@"number":@"",@"lat":@"29.57854",@"lon":@"106.580068"},@{@"number":@"8888888888",@"lat":@"29.57854",@"lon":@"106.780068"}]];
//    [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
- (void)addCarNumberAnnotation:(NSArray *)carNumberList{
  __block NSMutableArray *annotations = [NSMutableArray array];
  //移除原有的
  [self.mapView.annotations each:^(MAPointAnnotation *object) {
    if (object != self.userAnnotation) {
      [self.mapView removeAnnotation:object];
    }
  }];
  if (carNumberList.count <= 0) {
    return;
  }
  [carNumberList each:^(NSDictionary *object) {
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([object[@"lat"] doubleValue], [object[@"lon"] doubleValue]);
    GJNumberAnnotation *annotation = [[GJNumberAnnotation alloc]init];
    annotation.coordinate = coordinate;
    annotation.number = object[@"num"] ? object[@"num"] : @"";
    annotation.regionText = object[@"name"] ? object[@"name"] : @"";
    [annotations addObject:annotation];
  }];
  
  [self.mapView addAnnotations:annotations];
  //  [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
- (void)showUserLocation{
  MBProgressHUD *hud = [MBProgressHUD cr_showLoadinWithView:self text:@""];
  @weakify(self);
  __block NSInteger cycleTime = 5;
  [[GJLocationUtil shareInstance] getLocationWithCommplete:^(CLLocationCoordinate2D coordinate, NSDictionary * _Nonnull addressDic, NSError * _Nonnull error) {
    @strongify(self);
    if (error!=nil) {
      cycleTime --;
      if (cycleTime<=0) {
        [hud cr_hide];
        [MBProgressHUD cr_showToastWithView:self text:@"获取位置信息失败"];
        [[GJLocationUtil shareInstance] stopSerialLocation];
      }
      return;
    }
    [hud cr_hide];
    //停止更新位置信息
    [[GJLocationUtil shareInstance] stopSerialLocation];
    //展示我的位置图标
    [self.mapView setCenterCoordinate:coordinate animated:YES];
    if (self.userAnnotation) {
      [self.mapView removeAnnotation:self.userAnnotation];
    }
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc]init];
    annotation.coordinate = coordinate;
    [self.mapView addAnnotation:annotation];
    self.userAnnotation = annotation;
    [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
  }];
}
- (void)showUserLocationAnnotation:(NSDictionary *)dataDic{
  if (self.userAnnotation) {
    [self.mapView removeAnnotation:self.userAnnotation];
  }
  CLLocationCoordinate2D coordinate =  CLLocationCoordinate2DMake([dataDic[@"latitude"] doubleValue], [dataDic[@"longitude"] doubleValue]);
  //展示我的位置图标
  [self.mapView setZoomLevel:13];
  [self.mapView setCenterCoordinate:coordinate animated:YES];
  MAPointAnnotation *annotation = [[MAPointAnnotation alloc]init];
  annotation.coordinate = coordinate;
  [self.mapView addAnnotation:annotation];
  self.userAnnotation = annotation;
//  [[GJLocationUtil shareInstance] zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
- (void)setMapCenterWithLocation:(NSDictionary *)locationDic{
  if (locationDic) {
    CLLocationCoordinate2D coordinate =  CLLocationCoordinate2DMake([locationDic[@"lat"] doubleValue], [locationDic[@"lon"] doubleValue]);
    [self.mapView setCenterCoordinate:coordinate animated:YES];
  }
}
#pragma mark -- btnAction
- (void)buttonClickAction:(UIButton *)sender{
  switch (sender.tag) {
    case 101:
    {
      //locationBtn
    }
      break;
    default:
      break;
  }
}
- (void)dispatchGoodsButtonAction{
  
}

#pragma mark -- MAMapViewDelegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
  if ([overlay isKindOfClass:[MAPolyline class]]) {
    MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
    polylineRenderer.strokeColor = HexColor(#57A5FF);
    polylineRenderer.lineWidth   = 4.f;
    polylineRenderer.lineJoinType = kMALineJoinRound;
    polylineRenderer.lineCapType = kMALineCapRound;
    return polylineRenderer;
  }
  return nil;
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
  if ([annotation isKindOfClass:[GJOrderAnnotaion class]]) {
    GJOrderAnnotaion *gjAnnotation = (GJOrderAnnotaion *)annotation;
    static NSString *reuseIndetifier = @"gjOrderannotationReuseIndetifier";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
      annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                    reuseIdentifier:reuseIndetifier];
    }
    //根据RN传过来的图片名称进行显示
    annotationView.image = [UIImage imageNamed:gjAnnotation.icon];
    return annotationView;
  }else if([annotation isKindOfClass:[GJNumberAnnotation class]]){
    GJNumberAnnotation *gjAnnotation = (GJNumberAnnotation *)annotation;
    static NSString *reuseIndetifier = @"GJNumberAnnotationView";
    GJNumberAnnotationView *annotationView = (GJNumberAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
      annotationView = [[GJNumberAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:reuseIndetifier];
    }
    annotationView.numberText = gjAnnotation.number;
    annotationView.regiontext =  gjAnnotation.regionText;
    [annotationView setSelected:YES animated:YES];
    return annotationView;
  }else if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
    static NSString *reuseIndetifier = @"annotationReuseIndetifier";
    MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    if (annotationView == nil)
    {
      annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                    reuseIdentifier:reuseIndetifier];
    }
    
    annotationView.image = [self.locationIcon gj_hasValue] ? [UIImage imageNamed:self.iconNameDic[self.locationIcon]] : [UIImage imageNamed:@"mapModule_position_selected"];
    return annotationView;
  }
  return nil;
}
- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction{
  int zoomLevel =  mapView.zoomLevel;
  if (self.zoomLevel == zoomLevel) {
    return;
  }
  self.zoomLevel = zoomLevel;
  if (wasUserAction) {
    [GJUtil sendNotificationForRNEventEmitterWithActionKey:@"MAP_ZOOM_LEVEL" parameter:@{@"zoomLevel":[NSString stringWithFormat:@"%d",zoomLevel], @"latitude": @(self.mapView.centerCoordinate.latitude), @"longitude":@(self.mapView.centerCoordinate.longitude)}];
  }
}
#pragma mark -- getter
- (UIButton *)locationBtn{
  if (!_locationBtn) {
    _locationBtn = [UIButton new];
    [_locationBtn setImage:[UIImage imageNamed:@"mapModule_location"] forState:UIControlStateNormal];
    _locationBtn.tag = 101;
    [_locationBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
  }
  return _locationBtn;
}

- (MAMapView *)mapView{
  if (!_mapView) {
    _mapView = [[MAMapView alloc] initWithFrame:CGRectZero];
    //设置mapView的代理
    _mapView.delegate = self;
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = MAUserTrackingModeNone;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.zoomLevel = 13;
    [_mapView setZoomLevel:13];
    for (UIView *view in _mapView.subviews) {
      if ([view isKindOfClass:[UIImageView class]]) {
        [view removeFromSuperview];
      }
    }
  }
  return _mapView;
}
- (UIView *)dispatchGoodsButton{
  if (!_dispatchGoodsButton) {
    _dispatchGoodsButton = [UIView new];
    _dispatchGoodsButton.layer.masksToBounds = YES;
    _dispatchGoodsButton.layer.cornerRadius = KDispatchGoodsButtonWidth * 0.5;
    _dispatchGoodsButton.backgroundColor = [UIColor whiteColor];
    
    UIView *colorView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KDispatchGoodsSubViewWidth, KDispatchGoodsSubViewWidth)];
    colorView.layer.masksToBounds = YES;
    colorView.layer.cornerRadius = KDispatchGoodsSubViewWidth * 0.5;
    /**
     *  1.通过CAGradientLayer 设置渐变的背景。
     */
    CAGradientLayer *layer = [CAGradientLayer new];
    //colors存放渐变的颜色的数组
    layer.colors=@[(__bridge id)HexColor(#E5B867).CGColor,(__bridge id)HexColor(#BB934B).CGColor];
    /**
     * 起点和终点表示的坐标系位置，(0,0)表示左上角，(1,1)表示右下角
     */
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(1, 1);
    layer.frame = CGRectMake(0, 0, KDispatchGoodsSubViewWidth, KDispatchGoodsSubViewWidth);
    [colorView.layer addSublayer:layer];
    [_dispatchGoodsButton addSubview:colorView];
    [colorView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.center.equalTo(_dispatchGoodsButton);
      make.width.height.mas_equalTo(KDispatchGoodsSubViewWidth);
    }];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"map_dispatchGoods"]];
    [colorView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.width.height.mas_equalTo(21);
      make.top.mas_equalTo(12);
      make.centerX.equalTo(colorView);
    }];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
    label.text = @"去发货";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = kBoldSystemFontOfSize(10);
    [colorView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.right.centerX.equalTo(colorView);
      make.bottom.mas_equalTo(-9);
      make.top.equalTo(imageView.mas_bottom).offset(4);
    }];
    @weakify(self);
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
      //点击事件
      @strongify(self);
      [self dispatchGoodsButtonAction];
    }];
    [_dispatchGoodsButton addGestureRecognizer:gesture];
  }
  return _dispatchGoodsButton;
}
- (NSDictionary *)iconNameDic{
  if (!_iconNameDic) {
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"RNIconNameToOC"ofType:@"plist"];

    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];


    _iconNameDic = dictionary;
  }
  return _iconNameDic;
}
#pragma mark -- setter
-(void)setResIndex:(NSString *)resIndex{
  _resIndex = resIndex;
}
- (void)setLocationIcon:(NSString *)locationIcon{
  _locationIcon = locationIcon;
}
@end
